<template>
  <div>
    <div class="sys-org-index">
      <el-container>
        <el-main>
          <el-row>
            <el-form :inline="true" size="small" :model="searchForm" class="demo-form-inline" @keyup.enter.native="initData" @submit.native.prevent>
              <el-form-item>
                <el-button  type="primary" icon="el-icon-plus" @click="addOrg()" v-if="permissions.indexOf('org_sysOrg_add') > -1">添加</el-button>
              </el-form-item>
              <el-form-item>
                <el-input v-model="searchForm.name" placeholder="请输入部门名称" />
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-search" type="primary"  @click="initData()">查询</el-button>
                <el-button class="margin-left-10" icon="el-icon-delete" @click="resetOrg()">清空</el-button>
              </el-form-item>
              <el-tooltip effect="dark" content="刷新" placement="top-start">
                <el-button size="small" style="float: right;" icon="el-icon-refresh" @click="initData()" circle></el-button>
              </el-tooltip>
            </el-form>
          </el-row>
          <el-table
            :data="sysOrgPageData"
            style="width: 100%"
            row-key="id"
            border
            lazy
            default-expand-all
            :expand-row-keys="expands"
            size="mini"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column
              prop="name"
              label="部门名称"
              align="center"
              width="220"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              prop="orgDuty"
              align="center"
              label="部门职责"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              prop="desrc"
              align="center"
              label="描述"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              prop="createTime"
              align="center"
              label="创建时间"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="240" align="center">
              <template slot-scope="scope" >
                <el-button type="text" size="small" icon="el-icon-edit" @click="editOrg(scope.row)" v-if="permissions.indexOf('org_sysOrg_edit') > -1">编辑</el-button>
                <el-button type="text" size="small" icon="el-icon-delete" @click="delOrg(scope.row)" v-if="permissions.indexOf('org_sysOrg_del') > -1">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
    </div>
    <el-dialog
      customClass="dialog-form"
      :title="title" width="680px"
      :visible.sync="showDialog"
      @close="close"
      :close-on-click-modal="false"
      append-to-body="true">
      <el-container>
        <el-main>
          <el-form
            ref="form"
            :inline="true"
            :model="form"
            label-width="80px"
            :rules="rules">
            <el-form-item label="名称" ref="name" prop="name">
              <el-input placeholder="请输入部门名称"  v-model="form.name"/>
            </el-form-item>
            <el-form-item label="类型" ref="type" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型" :disabled="title==='编辑'" @change="changeSelet()">
                <el-option
                  v-for="item in options"
                  :key="item.type"
                  :label="item.name"
                  :value="item.type"
                  >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上级部门"   prop="parentName" v-if="form.type !== 'top'">
              <el-select
                v-model="form.parentName"
                allow-create
                default-first-option
                :disabled="title==='编辑'"
                placeholder="请选择上级部门"
                popper-class="select-box"
                ref="selectBox"
                >
                <el-option>
                  <el-tree
                    class="filter-tree"
                    node-key="id"
                    :data="sysOrgPageData"
                    :props="defaultProps"
                    ref="selectTree"
                    highlight-current
                    @node-click="handleNodeClick">
                  </el-tree>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="部门职责" prop="orgDuty" class="form-textarea-count">
              <el-input type="textarea" :rows="2" placeholder="请输入部门职责" v-model="form.orgDuty" maxlength="20" show-word-limit/>
            </el-form-item>
            <el-form-item label="描述" prop="desrc" class="form-textarea-count">
              <el-input type="textarea" :rows="2" placeholder="请输入描述" v-model="form.desrc" maxlength="20" show-word-limit/>
            </el-form-item>
          </el-form>
        </el-main>
      </el-container>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-plus-outline" size="small" @click="saveForm()" type="primary">确 定</el-button>
        <el-button icon="el-icon-circle-close" size="small" @click="close()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import sysOrgApi from "./api/sysOrg.service";

export default {
  data () {
    return {
      rules: {
        name: [
          {
            required: true,
            message: "部门名称不能为空！",
            trigger: "blur"
          },
          {
            max:10,
            message: "部门名称长度不能超过10个字符！",
            trigger: "blur"
          }
        ],
        type: [
          {
            required: true,
            message: "请选择类型！",
            trigger: "blur"
          }
        ],
        parentName: [
          {
            required: true,
            message: "请选择上级部门！",
            trigger: "blur"
          }
        ],
        orgDuty: [
          {
            required: true,
            message: "职责不能为空！",
            trigger: "blur"
          }
        ],
        desrc: [
          {
            required: true,
            message: "描述不能为空！",
            trigger: "blur"
          }
        ],
      },
      permissions: JSON.parse(sessionStorage.getItem("permissions")),
      title: '',
      expands: [],
      getRowKeys (row) {
        return row.id
      },
      showDialog: false,
      sysOrgPageData: [],
      form: {
        name: '',
        type: '',
        parentId: '',
        parentName: '',
        orgDuty: '',
        desrc: ''
      },
      searchForm: {
        name: ''
      },
      defaultProps: {
        children: "children",
        label: "name"
      },
      options: [
        {
          type: 'top',
          name: "顶部门"
        },
        {
          type: 'common',
          name: "部门"
        }
      ],
      allNodeIds: []
    }
  },
  created () {
    this.initData()
  },
  methods: {
    // 点击部门树
    handleNodeClick(data) {
      this.form.parentId = data.id;
      this.form.parentName = data.name;
      this.$refs.selectBox.blur()
    },
    // 类型
    changeSelet(val) {
      if (this.form.type == 'top') {
        this.form.parentId = 0;
        this.form.parentName = ''
      }
    },
    resetOrg () {
      this.searchForm.name = '';
      this.initData()
    },
    // init
    initData() {
      let _this = this;
      sysOrgApi.getSysOrgTree({orgName: this.searchForm.name}).then(res => {
        if (res.code == 10200) {
          _this.sysOrgPageData = res.data
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 添加
    addOrg () {
      let obj  = {
        name: '',
        type: '',
        parentId: '',
        parentName: '',
        orgDuty: '',
        desrc: ''
      };
      this.form = obj;
      this.title = "添加";
      this.showDialog = true;
    },
    // 编辑
    editOrg (row) {
      let obj  = {
        name: row.name,
        type: row.type,
        parentId: row.parentId,
        parentName: row.parentName,
        orgDuty: row.orgDuty,
        desrc: row.desrc,
        id: row.id
      };
      this.form = obj;
      this.title = "编辑";
      this.showDialog = true;
    },
    // 关闭
    close() {
      this.$refs["form"].resetFields();
      this.showDialog = false;
    },
    // 保存
    saveForm () {
      let _this = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title === "添加") {
            sysOrgApi.saveSysOrg(_this.form).then(res => {
              if (res.code == 10200) {
                this.$message.success("添加成功！");
                _this.initData();
                _this.close()
              } else {
                this.$message.error(res.msg);
              }
            });
          } else {
            sysOrgApi.updateSysOrgById(_this.form).then(res => {
              if (res.code == 10200) {
                this.$message.success("修改成功！");
                _this.initData();
                _this.close()
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        }
      })
    },
    // 删除
    delOrg (row) {
      this.allNodeIds = [];
      this.allNodeIds.push(row.id);
      if (row.children&&row.children.length > 0) {
        this.getTreeNodes(row)
      }
      this.$confirm("本操作将永久删除部门，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        sysOrgApi.removeByIds(this.allNodeIds).then(res => {
          if (res.code == 10200) {
            this.$message.success("删除成功！");
            this.initData();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    getTreeNodes(arr) {
      let arrTree = arr;
      arrTree.children.forEach(item => {
        this.allNodeIds.push(item.id);
        if (item.children&&item.children.length > 0) {
          this.getTreeNodes(item)
        }
      });

    },

  }
}
</script>
<style scoped>
.sys-org-index {
  padding-bottom: 50px;
}
</style>
